﻿using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoWordAltChunk
{
    class Program
    {
        private const string url = "http://spvm/sites/demoopenxml";
        static void Main(string[] args)
        {
            Console.WriteLine("/*Génération Document WORD ALTCHUNK Sample*/\n");
            GenerateDocument();
            Console.WriteLine("/*Fin*/\n");
            Console.ReadKey();
        }

        private static void GenerateDocument()
        {
            Stream docstream = null;
            using (SPSite site = new SPSite(url))
            {
                SPWeb web = site.OpenWeb();
                SPFile spf = web.GetFile("Shared Documents/WORD_ALTCHUNK_TEMPLATE.docx");
                if (!spf.Exists)
                {
                    Console.WriteLine("Le Document n'éxiste pas\n");
                }
                else
                {
                    docstream = spf.OpenBinaryStream();
                }
                if (docstream != null)
                {
                    Console.WriteLine("Début de la phase de WordAltchunkProcessing\n");
                    using (WordprocessingDocument outDoc = WordprocessingDocument.Open(docstream, true))
                    {
                        MainDocumentPart mainPart = outDoc.MainDocumentPart;
               
                        SPList spList = web.Lists.TryGetList("demo");
                        if (spList != null)
                        {
                            SPQuery qry = new SPQuery();
                            qry.ViewFields = @"<FieldRef Name='Description' />";
                            SPListItemCollection listitems = spList.GetItems(qry);
                            foreach (SPListItem item in listitems)
                            {
                                /*HTML-RTE*/
                                HtmlBuilder html_builder = new HtmlBuilder();
                                StringBuilder xhtmlBuilder = html_builder.BuilderHtml(item["Description"].ToString());
                                AltChunkMethod(outDoc, xhtmlBuilder.ToString(), "altchunk", "chunkid");
                                
                            }
                            

                        }

                    }


                   
                    CREATE_OUTPUT_DOC(web, docstream, "OUT_WORD_ALTCHUNK_TEMPLATE", ".docx");
                }
            }
        }

        
        protected static void AltChunkMethod(WordprocessingDocument outDoc, string htmlbuilder, string alias, string chunkid)
        {
            string altChunkId = chunkid;//se doit d'être unique
            AlternativeFormatImportPart chunk = outDoc.MainDocumentPart.AddAlternativeFormatImportPart
                (AlternativeFormatImportPartType.Xhtml, altChunkId);
            
            //Utilisation en mémoire d'html
            using (MemoryStream xhtmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlbuilder)))
            {
                chunk.FeedData(xhtmlStream);//Injection html

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                //Parcours dans le document à la recherche d'alias
                var resprocess = from bm in outDoc.MainDocumentPart.Document.Body.Descendants<SdtAlias>()
                                 where bm.Val.Value == alias
                                 select bm;
                var process = resprocess.SingleOrDefault();
                var parent = process.Parent;

                parent.InsertAfterSelf(altChunk);//Insertion dans le ContentControl
                
            }
        }
        private static void CREATE_OUTPUT_DOC(SPWeb web, Stream outputStream, string filename, string ext)
        {
            try
            {
                SPList outputLibrary = web.Lists.TryGetList("Documents");
                if (outputLibrary != null)
                {
                    string outputFileUrl = string.Format("{0}/{1}", outputLibrary.RootFolder.ServerRelativeUrl, filename + ext);
                    web.AllowUnsafeUpdates = true;
                    outputLibrary.RootFolder.Files.Add(outputFileUrl, outputStream);
                    web.Update();
                    if (outputStream != null)
                    {
                        outputStream.Dispose();
                    }
                    Console.WriteLine("Le Document a bien été généré\n");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erreur de création de Document\n :" + ex.ToString());
            }
        }
    
    }
}
